'use strict';

const appId = 'wxb4f527bd11796c0e'
const appSecret = '290a21e79bbcc03305a93df5aa377832'
const db = uniCloud.database();
exports.main = async (event, context) => {
	//获取前端参数
	const {
		code,
		nickName,
		gender,
		city,
		province,
		country,
		avatarUrl
	} = event;
	//获取openid
	const res = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`, {
			dataType: "json"
		}
	)
	let openid = res.data.openid;

	//获取user表
	const collection = db.collection('user');

	// 生成token
	// 新增并返回用户信息
	let userData = {
		nickName,
		gender,
		city,
		province,
		country,
		avatarUrl,
		openid
	}

	const datas = await collection.where({
		openid: userData.openid,
	}).get()
	debugger
	console.log(datas.affectedDocs);
	if (datas.affectedDocs == 0) {
		const resData = await db.collection("user").add(userData)
	}

	//将用户信息返回前端
	let data = {
		nickName,
		gender,
		city,
		province,
		country,
		avatarUrl,
	}
	return {
		code: 200,
		msg: '登录成功',
		data: {
			userInfo: datas.data[0] ? datas.data[0] : resData.data,
		}
	}
};